import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { InputNumber, Select, message } from 'antd';
import 'moment/locale/zh-cn';
import { TableC } from '../../../../comps';
import myStyle from '../index.less';
import colors from '../../../../css/colors';

const { Option } = Select;

@connect(({ portfolioOptimizationM, loading }) => ({
  portfolioOptimizationM,
  loading,
}))
@Form.create()
export default class FormTableC extends PureComponent {
  state = {
    timeOutGap: 500,
    dataSource: [{ order: '总计', initWeight: 0 }], //表格数据
    errorMsg: '', //错误提示消息
    assetList: [], //资产下拉列表
  };

  componentDidMount() {
    this.props.onRef(this);
    this.addRow(); //默认新增一条
  }
  componentWillUnmount() {
    // 离开前清除models数据
  }

  //新增一行
  addRow = () => {
    const { dataSource } = this.state;
    if (dataSource.length == 1) {
      //总计 在最后一条
      dataSource.splice(0, 0, {
        order: dataSource.length,
      });
    } else {
      dataSource.splice(dataSource.length - 1, 0, {
        //其余每次在倒数第一行 和 总计 这一行 中间插入
        order: dataSource.length,
      });
    }
    this.setState({
      dataSource: [...dataSource],
    });
  };

  //删除一行
  delRow = (row) => {
    const { dataSource } = this.state;
    const arr = dataSource.filter((item) => {
      return item.order != row.order;
    });
    arr.map((item, index) => {
      if (item.order != '总计') {
        //删除之后 重置序号
        item.order = index + 1;
      }
    });
    this.setState(
      {
        dataSource: [...arr],
      },
      () => {
        this.calcWeight(); //重新计算权重之和
      },
    );
  };

  //计算权重之和
  calcWeight = () => {
    const { dataSource } = this.state;
    let sum = 0;
    dataSource.map((item, index) => {
      if (index != dataSource.length - 1) {
        sum = sum + (item.initWeight * 1 || 0);
      }
    });
    dataSource[dataSource.length - 1].initWeight = sum;
    this.setState({
      dataSource: [...dataSource],
    });
  };

  //校验每行数据
  checkObj = (arr, obj) => {
    for (var i = 0; i < arr.length; i++) {
      let key = arr[i];
      if (obj[key] !== 0 && !obj[key]) {
        this.setState({
          errorMsg: '请设置完整的条件!',
        });
        return key;
      }
    }
    return null;
  };

  //表格提交
  submit = () => {
    const { dataSource, errorMsg } = this.state;
    const { initColumns } = this.props;
    var msg = '';
    var columnKeys = [];
    initColumns.map((item) => {
      //选中的column对应的key
      if (item.isNeed) {
        columnKeys.push(item.key);
      }
    });
    if (dataSource.length == 1) {
      msg = '请点击加号图标进行新增数据!';
      this.setState({
        errorMsg: msg,
      });
      return null;
    }
    if (dataSource.length < 3) {
      msg = '至少添加2行数据!';
      this.setState({
        errorMsg: msg,
      });
      return null;
    }
    for (var i = 0; i < dataSource.length; i++) {
      var item = dataSource[i];
      item.isRed = false;
      if (item.order != '总计') {
        var index = this.checkObj(columnKeys, item);
        if (index) {
          item.isRed = true;
          this.setState({
            dataSource: [...dataSource],
          });
          return null;
        }
        if (item.weightBottom && item.weightTop &&columnKeys.includes("weightTop")) {
          if (item.weightBottom > item.weightTop || item.weightBottom == item.weightTop) {
            msg = '权重上界必须大于权重下界';
            this.setState({
              errorMsg: msg,
            });
            item.isRed = true;
            this.setState({
              dataSource: [...dataSource],
            });
            return null;
          }
        }
      } else if (!(Number(item.initWeight.toFixed(2)) > 99.99 && Number(item.initWeight.toFixed(2) < 100.01))) {
        msg = '初始权重总计必须为100%,请手动调整或者点击相关设置-配置权重。';
        this.setState({
          errorMsg: msg,
        });
        return null;
      }
    }

    this.setState({
      errorMsg: '',
    });
    return dataSource;
  };

  //父组件点击重置按钮
  reset = () => {
    this.setState(
      {
        dataSource: [{ order: '总计', initWeight: 0 }],
        errorMsg: '', //错误提示消息
      },
      () => {
        this.addRow(); //默认新增一条
      },
    );
  };

  //配置权重
  setWeightBytype = (val) => {
    const { dataSource, weightMethodList } = this.state;
    if (dataSource.length < 2) return; //没有新增不进行计算
    if (val == '0') {
      //等权重
      dataSource.map((item, index) => {
        if (index != dataSource.length - 1) {
          item.initWeight = 100 / (dataSource.length - 1);
        } else {
          item.initWeight = 100;
        }
      });
    } else if (val == '1') {
      //归一化
      dataSource.map((item, index) => {
        var sum = dataSource[dataSource.length - 1].initWeight;
        if (index != dataSource.length - 1) {
          item.initWeight = sum === 0 ? undefined : parseFloat((item.initWeight || 0) / sum) * 100;
        } else {
          item.initWeight = sum == 0 ? 0 : 100;
        }
      });
    } else {
      //清空
      dataSource.map((item, index) => {
        if (index != dataSource.length - 1) {
          delete item.initWeight;
        } else {
          item.initWeight = 0;
        }
      });
    }
  };

  //模糊搜索资产下拉
  handleSearch = (e) => {
    const { dispatch } = this.props;
    const { timeOutGap } = this.state;
    if (e) {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        dispatch({
          type: 'portfolioOptimizationM/queryAsset',
          payload: {
            name: e,
            type: this.props.type,
          },
          callback: (res) => {
            if (res) {
              if (res.code == 0) {
                this.setState({
                  assetList: [...res.data.slice(0, 20)],
                });
              } else {
                message.error(res.msg || '查询资产下拉列表失败!');
              }
            } else {
              message.error('查询资产下拉列表失败!');
            }
          },
        });
      }, timeOutGap);
    }
  };

  //初始化表格
  initTable = () => {
    const { initColumns, groupData = [], typeStatus } = this.props;
    const { dataSource, errorMsg, assetList } = this.state;
    let columns = initColumns.filter((item) => item.isNeed == true); //过滤需要展示的列
    let currentHeight = document.getElementById('tabDiyWidth') ? document.getElementById('tabDiyWidth').offsetHeight - 580 : 140;
    columns.map((item) => {
      if (item.key != 'order' || item.key != 'operate') {
        if (item.key != 'asset' && typeStatus != '3') item.width = parseFloat(90 / columns.length) - 1 + '%'; //设置宽度
        if (item.key == 'asset') {
          item.align = 'right';
          item.render = (text, record) => {
            //设置展示的form表单 资产
            if (record.order == '总计') return text; //总计行展示
            return typeStatus != 3 ? (
              <Select
                className={errorMsg && record.isRed ? 'has-error' : ''}
                value={record[item.key]}
                style={{ width: '100%' }}
                labelInValue
                showSearch
                onSearch={this.handleSearch}
                filterOption={false}
                onChange={(val) => {
                  record[item.key] = val;
                  dataSource.map((row) => {
                    if (row.order == record.order) {
                      row = { ...record };
                    }
                  });
                  this.setState({
                    //渲染表格,使修改生效
                    dataSource: [...dataSource],
                  });
                }}
              >
                {assetList &&
                  assetList.map((item, index) => {
                    return (
                      <Option value={item.value} key={item.value}>
                        {item.title}
                      </Option>
                    );
                  })}
              </Select>
            ) : (
              text?.label
            );
          };
        } else if (item.key == 'group') {
          item.render = (text, record) => {
            //设置展示的form表单 组别
            if (record.order == '总计') return text; //总计行展示
            let tempObj = groupData.filter((x) => x.id == text)?.length ? groupData.filter((x) => x.id == text)[0] : {};
            return typeStatus != '3' ? (
              <Select
                className={errorMsg && record.isRed ? 'has-error' : ''}
                value={record[item.key]}
                style={{ width: '100%' }}
                onChange={(val) => {
                  record[item.key] = val;
                  dataSource.map((row) => {
                    if (row.order == record.order) {
                      row = { ...record };
                    }
                  });
                  this.setState({
                    //渲染表格,使修改生效
                    dataSource: [...dataSource],
                  });
                }}
              >
                {groupData &&
                  groupData.map((x, index) => {
                    return (
                      <Option value={x.id} key={index}>
                        {x.group}
                      </Option>
                    );
                  })}
              </Select>
            ) : (
              tempObj['group']
            );
          };
        } else {
          item.render = (text, record) => {
            //设置展示的form表单
            if (record.order == '总计') {
              //总计行展示
              if (item.key == 'initWeight') return (text * 1).toFixed(2) + '%';
              return text;
            }
            return typeStatus != '3' ? (
              <InputNumber
                value={record[item.key]}
                className={errorMsg && record.isRed ? 'has-error' : ''}
                min={0}
                max={100}
                step={0.1}
                precision={2}
                placeholder={'请输入0-100的数字'}
                style={{ width: '100%' }}
                onChange={(value) => {
                  var pattern = /^(\+)?\d+(\.\d+)?$/;
                  if (!pattern.test(value)) return; //只允许>0 数字和小数时调用
                  if (value > 100) return;
                  record[item.key] = value;
                  dataSource.map((row) => {
                    if (row.order == record.order) {
                      row = { ...record };
                    }
                  });
                  this.setState({
                    //渲染表格,使修改生效
                    dataSource: [...dataSource],
                  });
                  if (item.key == 'initWeight') {
                    //实时更新权重总计
                    this.calcWeight();
                  }
                }}
              />
            ) : (
              (text * 1).toFixed(2)
            );
          };
        }
      }
    });
    if (columns && columns.length && columns[columns.length - 1].key != 'operate') {
      columns.unshift({
        key: 'order',
        title: '序号',
        width: 100,
        align: 'center',
        render: (text) => {
          return text < 10 ? `0${text}` : text;
        },
      });
      if (typeStatus != '3')
        columns.push({
          key: 'operate',
          title: '操作',
          width: 50,
          align: 'left',
          render: (text, record) => {
            if (record.order == '总计') return text; //总计行展示
            return (
              <MinusCircleOutlined
                style={{ color: colors.debtAndProfit.text[0], fontSize: '16px' }}
                onClick={() => {
                  this.delRow(record);
                }}
              />
            );
          },
        });
    }
    return <TableC columns={columns} dataSource={dataSource} rowKey='order' hidePage={true} scroll={{ x: '100%', y: 224 }} />;
  };

  render() {
    const { errorMsg } = this.state;

    return (
      <div className={myStyle.tableForm}>
        {this.initTable()}
        {this.props.typeStatus != '3' && (
          <div className='addRow' style={this.props.barraConst == 0 ? { border: 0, paddingLeft: '110px' } : { paddingLeft: '110px' }}>
            <PlusCircleOutlined onClick={this.addRow} />
            <span style={{ display: errorMsg ? 'inherit' : 'none', color: colors.debtAndProfit.text[0] }}>{errorMsg}</span>
          </div>
        )}
      </div>
    );
  }
}
